<template>
  <ContentWrap>
    <!-- 搜索工作栏：保持不变 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="航机员" prop="flightCrew">
        <el-input
          v-model="queryParams.flightCrew"
          placeholder="请输入航机员"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="进港航班" prop="inboundFlight">
        <el-input
          v-model="queryParams.inboundFlight"
          placeholder="请输入进港航班"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="预落时间" prop="preLandingTime">
        <el-input
          v-model="queryParams.preLandingTime"
          placeholder="请输入预落时间(HHmm)"
          clearable
          @input="handleTimeInput('preLandingTime', $event)"
          @blur="handleTimeBlur('preLandingTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="实落时间" prop="inboundTime">
        <el-input
          v-model="queryParams.inboundTime"
          placeholder="请输入实落时间(HHmm)"
          clearable
          @input="handleTimeInput('inboundTime', $event)"
          @blur="handleTimeBlur('inboundTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-input
          v-model="queryParams.depTime"
          placeholder="请输入起飞时间(HHmm)"
          clearable
          @input="handleTimeInput('depTime', $event)"
          @blur="handleTimeBlur('depTime')"
          @keyup.enter="handleQuery"
          class="!w-240px"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-input
          v-model="queryParams.flightNo"
          placeholder="请输入航班号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="机号" prop="machineNo">
        <el-input
          v-model="queryParams.machineNo"
          placeholder="请输入机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="记录日期" prop="recordDate">
        <el-date-picker
          v-model="queryParams.recordDate"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="选择记录日期"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openCreForm('create')"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 获取最新
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleSyncQuarter"
          v-hasPermi="['distm:schedule-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 同步季度计划
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:schedule-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 列设置按钮 -->
        <el-button type="primary" plain @click="openColumnSetting">
          <Icon icon="ep:setting" class="mr-5px" /> 列设置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：虚拟化表格 -->
  <ContentWrap>
    <div style="height: 62vh">
      <TableV2
        :columns="tableV2Columns"
        :data="list"
        height="62vh"
        :loading="loading"
        :table-set-props="{
          fixed: true,
          rowClassName: tableRowClassName,
          rowHeight: 70
        }"
      />
      <!-- <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2
            :columns="tableV2Columns"
            :data="list"
            :width="width"
            :height="height"
            fixed
            :loading="loading"
            :row-class="tableRowClassName"
            :row-height="70"
          />
        </template>
      </el-auto-resizer> -->
    </div>
  </ContentWrap>

  <!-- 列设置弹窗：保持不变 -->
  <el-dialog
    title="表格列设置"
    v-model="columnSettingVisible"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-checkbox-group v-model="selectedColumns" class="column-setting-group">
      <el-checkbox
        v-for="column in tableColumns"
        :key="column.prop"
        :label="column.prop"
        style="width: 25%"
      >
        {{ column.label }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="columnSettingVisible = false">取消</el-button>
      <el-button type="primary" @click="saveColumnSettings">确定</el-button>
    </template>
  </el-dialog>

  <!-- 数量编辑弹窗 -->
  <el-dialog
    title="编辑数量信息"
    v-model="quantityDialogVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form ref="quantityFormRef" :model="currentRow" label-width="120px">
      <el-form-item label="销售数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewSaleQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassSaleQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassSaleQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassSaleQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="配餐数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="quantityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleQuantitySave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 新增：时间详情弹窗 - 时间修改格式与外部表格一致 -->
  <el-dialog
    title="航班时间详情"
    v-model="timeDetailDialogVisible"
    width="1400px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-table
      :data="timeDetailData"
      style="width: 100%"
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{ 'text-align': 'center', 'font-weight': 'bold' }"
    >
      <el-table-column label="航班号" prop="flightNo" width="120" />
      <el-table-column label="进港时间" prop="inboundTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.inboundTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'inboundTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'inboundTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="预落时间" prop="preLandingTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.preLandingTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'preLandingTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'preLandingTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="机位" prop="airportStands" width="100">
        <template #default="scope">
          <el-input
            v-model="scope.row.airportStands"
            placeholder="请输入机位"
            clearable
            @blur="handleFieldBlur(scope.row, 'airportStands')"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="实落时间" prop="shiLuoTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.shiLuoTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'shiLuoTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'shiLuoTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="起飞时间" prop="depTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.depTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'depTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'depTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="预飞时间" prop="yuFeiTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.yuFeiTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'yuFeiTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'yuFeiTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="实飞时间" prop="shiFeiTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.shiFeiTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'shiFeiTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'shiFeiTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="回港时间" prop="arrTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.arrTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'arrTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'arrTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="预回时间" prop="yuHuiTime" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.yuHuiTime"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'yuHuiTime', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'yuHuiTime', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="回位" prop="huiWei" width="100">
        <template #default="scope">
          <el-input
            v-model="scope.row.huiWei"
            placeholder="请输入回位"
            clearable
            @blur="handleFieldBlur(scope.row, 'huiWei')"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="实回时间" prop="shiHui" width="120">
        <template #default="scope">
          <el-input
            v-model="scope.row.shiHui"
            placeholder="HHmm"
            clearable
            @input="handleColumnTimeInput(scope.row, 'shiHui', $event)"
            @blur="handleColumnTimeBlur(scope.row, 'shiHui', true)"
            class="!w-full"
            show-word-limit
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否延误" prop="yanWu" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.yanWu"
            active-text="是"
            inactive-text="否"
            @change="handleFieldBlur(scope.row, 'yanWu')"
            :disabled="scope.row.pstatus === 12"
          />
        </template>
      </el-table-column>
    </el-table>
    <!-- 去掉保存按钮，只保留取消按钮 -->
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件：保持不变 -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <ProduceRecordForm ref="formRef" @success="getList" />
  <ScheduleRecordForm ref="formCreRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import type { Column } from 'element-plus'
import {
  ElInput,
  ElButton,
  ElTag,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon,
  ElTooltip,
  ElDialog,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElTable,
  ElTableColumn,
  ElSwitch
} from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  Setting,
  DArrowRight,
  Timer
} from '@element-plus/icons-vue'

// 保留原始业务导入
import { dateFormatter, formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import { ShiftRecordApi } from '@/api/pplan/shiftrecord'
import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import { DICT_TYPE } from '@/utils/dict'
import ScheduleRecordForm from '@/views/distm/schedule/ScheduleRecordForm.vue'

/** 基础配置：保持不变 */
defineOptions({ name: 'ScheduleRecord' })
const message = useMessage()
const { t } = useI18n()

// 状态管理：保持不变
const loading = ref(true)
const list = ref<ScheduleRecordVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5000,
  flightNo: undefined,
  depTime: undefined,
  flightCrew: undefined,
  inboundFlight: undefined,
  machineNo: undefined,
  inboundTime: undefined,
  preLandingTime: undefined,
  recordDate: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)

// 数量编辑弹窗相关
const quantityDialogVisible = ref(false)
const currentRow = ref<Partial<ScheduleRecordVO>>({})
const quantityFormRef = ref()

// 新增：时间详情弹窗状态
const timeDetailDialogVisible = ref(false)
const timeDetailData = ref<ScheduleRecordVO[]>([])
const originalTimeData = ref<ScheduleRecordVO[]>([]) // 用于回滚的原始数据

/** 生产状态：保持不变 */
const pstatusList = reactive([
  { value: 1, label: '餐食准备完成' },
  { value: 2, label: '机供品准备完成' },
  { value: 3, label: '任务分配完成' },
  { value: 4, label: '航机任务确认' },
  { value: 5, label: '装机' },
  { value: 6, label: '完成' },
  { value: 7, label: '发车确认' },
  { value: 8, label: '进入机坪' },
  { value: 9, label: '到达机位完成' },
  { value: 10, label: '开始保障' },
  { value: 11, label: '结束保障' },
  { value: 12, label: '起飞' },
  { value: 13, label: '取消装机' },
  { value: 14, label: '取消完成' }
])

/** 工具函数 */
const getStatusLabel = (statusValue: number | string | undefined | null) => {
  if (!statusValue && statusValue !== 0) return '未开始'
  const numStatus = Number(statusValue)
  const matched = pstatusList.find((item) => item.value === numStatus)
  return matched ? matched.label : '未开始'
}

// 统一的时间格式化函数
const formatTimeArray = (timeArr: any[] | string | object | undefined): string => {
  if (!timeArr) return ''
  if (Array.isArray(timeArr) && timeArr.length === 2) {
    const hour = String(timeArr[0]).padStart(2, '0')
    const minute = String(timeArr[1]).padStart(2, '0')
    return `${hour}:${minute}`
  }
  if (typeof timeArr === 'object' && 'hour' in timeArr && 'minute' in timeArr) {
    const hour = String((timeArr as any).hour).padStart(2, '0')
    const minute = String((timeArr as any).minute).padStart(2, '0')
    return `${hour}:${minute}`
  }
  if (typeof timeArr === 'string') {
    if (/^\d{4}$/.test(timeArr)) {
      return `${timeArr.slice(0, 2)}:${timeArr.slice(2, 4)}`
    }
    if (/^\d{2}:\d{2}$/.test(timeArr)) {
      return timeArr
    }
  }
  return String(timeArr)
}

const normalizeTimeFormat = (timeValue: any): string => {
  if (!timeValue) return ''
  return formatTimeArray(timeValue)
}

const formatTimeString = (timeString: string): string | null => {
  if (!timeString) return null
  if (timeString.includes(':')) return timeString
  if (!/^\d{4}$/.test(timeString)) return null
  const hours = parseInt(timeString.slice(0, 2))
  const minutes = parseInt(timeString.slice(2, 4))
  if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) {
    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
  }
  return null
}

const formatDisplayTime = (timeString: string | undefined): string | null => {
  if (!timeString) return null
  return formatTimeString(timeString)
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

// 判断是否是弹窗中的时间字段
const isDialogTimeColumn = (prop: string): boolean => {
  return [
    'inboundTime', 
    'preLandingTime', 
    'shiLuoTime', 
    'depTime', 
    'yuFeiTime', 
    'shiFeiTime', 
    'arrTime', 
    'yuHuiTime', 
    'shiHui'
  ].includes(prop)
}

const isNumberColumn = (prop: string): boolean => {
  return [
    'crewQty',
    'bussClassQty',
    'premEcoClassQty',
    'ecoClassQty',
    'crewSaleQty',
    'bussClassSaleQty',
    'premEcoClassSaleQty',
    'ecoClassSaleQty'
  ].includes(prop)
}

const getColumnNameByProp = (prop: string): string => {
  const column = tableColumns.find((col) => col.prop === prop)
  return column?.label || prop
}

/** 业务逻辑 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getScheduleRecordPage(queryParams)
    list.value = data.list || []
    list.value.forEach((item) => {
      item.inboundTime = normalizeTimeFormat(item.inboundTime)
      item.preLandingTime = normalizeTimeFormat(item.preLandingTime)
      item.depTime = normalizeTimeFormat(item.depTime)
      item._original = JSON.parse(JSON.stringify(item))
      item.formattedOriginal = {
        inboundTime: item.inboundTime || '',
        preLandingTime: item.preLandingTime || '',
        depTime: item.depTime || '',
        machineNo: item.machineNo || '',
        airportStands: item.airportStands || '',
        inboundFlight: item.inboundFlight || '',
        remarks: item.remarks || '',
        bussClassQty: item.bussClassQty || '',
        crewSaleQty: item.crewSaleQty || '',
        bussClassSaleQty: item.bussClassSaleQty || '',
        premEcoClassSaleQty: item.premEcoClassSaleQty || '',
        ecoClassSaleQty: item.ecoClassSaleQty || '',
        crewQty: item.crewQty || '',
        premEcoClassQty: item.premEcoClassQty || '',
        ecoClassQty: item.ecoClassQty || '',
        specialRemarks: item.specialRemarks || ''
      }
    })
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleQuery = () => getList()

const resetQuery = () => {
  if (queryFormRef.value) queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  formRef.value.openFlightNo(type, flightNo)
}

const formCreRef = ref()
const openCreForm = (type: string, id?: number) => {
  formCreRef.value.open(type, id)
}

const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  if (formAddRef.value && flightNo) formAddRef.value.openAdd('create', flightNo, recordDate)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ScheduleRecordApi.deleteScheduleRecord(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ScheduleRecordApi.exportScheduleRecord(queryParams)
    download.excel(data, '配送管理-调度生产记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleSyncQuarter = async () => {
  try {
    await message.exportConfirm('同步季度计划会重置今日计划和生产计划，是否同步季度计划？')
    exportLoading.value = true
    await ScheduleRecordApi.syncQuarterPlan()
    message.success('同步季度计划成功')
    await getList()
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 字段更新核心逻辑
const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }

    const hasChange = Object.keys(row).some((key) => {
      if (key === '_original' || key === 'formattedOriginal') return false
      const original = row.formattedOriginal?.[key] || ''
      const current = row[key] || ''
      if (isTimeColumn(key) || isDialogTimeColumn(key)) return original !== current
      if (isNumberColumn(key)) return String(original) !== String(current)
      return original !== current
    })

    if (!hasChange) return

    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      crewSaleQty: row.crewSaleQty ? Number(row.crewSaleQty) : undefined,
      bussClassSaleQty: row.bussClassSaleQty ? Number(row.bussClassSaleQty) : undefined,
      premEcoClassSaleQty: row.premEcoClassSaleQty ? Number(row.premEcoClassSaleQty) : undefined,
      ecoClassSaleQty: row.ecoClassSaleQty ? Number(row.ecoClassSaleQty) : undefined,
      crewQty: row.crewQty ? Number(row.crewQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO

    const res = await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(res !== 'success' ? res : t('common.updateSuccess'))

    // 更新原始值缓存
    if (row.formattedOriginal) {
      Object.keys(row.formattedOriginal).forEach(key => {
        if (key in row) {
          row.formattedOriginal[key] = row[key]
        }
      })
    } else {
      row.formattedOriginal = { ...row }
    }
    
  } catch (err) {
    console.error('更新失败:', err)
    message.error(t('common.updateFail'))
    // 发生错误时回滚数据
    await getList()
  }
}

// 数量编辑弹窗确认保存
const handleQuantitySave = async () => {
  try {
    if (!currentRow.value.id) {
      message.error('数据无效')
      return
    }
    const tempRow = JSON.parse(JSON.stringify(currentRow.value)) as ScheduleRecordVO
    await handleFieldChange(tempRow)
    quantityDialogVisible.value = false
    await getList()
  } catch (err) {
    console.error('数量更新失败:', err)
    message.error(t('common.updateFail'))
  }
}

const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    if (row.pstatus === newStatus) return
    await ScheduleRecordApi.updateScheduleRecord({ id: row.id, pstatus: newStatus })
    row.pstatus = newStatus
  } catch (err) {
    console.error('生产状态更新失败：', err)
  }
}

const importFormRef = ref()
const handleImportLog = () => importFormRef.value?.open()

/** 搜索栏时间输入处理 */
const handleTimeInput = (field: string, value: string, row: any = null) => {
  const target = row || queryParams
  target[field] = value.replace(/[^0-9]/g, '')
}

const handleTimeBlur = (field: string, row: any = null) => {
  const target = row || queryParams
  const value = target[field] || ''
  
  if (!value) return
  
  if (value.length !== 4 || !/^\d{4}$/.test(value)) {
    message.error(`请输入4位数字的${getColumnNameByProp(field)}格式(HHmm)`)
    target[field] = ''
    return
  }
  
  const hours = parseInt(value.substring(0, 2))
  const minutes = parseInt(value.substring(2, 4))
  
  if (hours >= 24 || minutes >= 60) {
    message.error('请输入有效的时间(HHmm)')
    target[field] = ''
    return
  }
  
  target[field] = `${value.substring(0, 2)}:${value.substring(2, 4)}`
}

/** 表格内输入框处理函数 */
const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  const numericValue = value.replace(/[^0-9]/g, '');
  row[prop] = numericValue.slice(0, 9);
};

// 修复后的时间输入框blur处理函数
const handleColumnTimeBlur = async (row: any, prop: string, isDialog = false) => {
  // 优先从行内的 formattedOriginal 获取原始值
  const original = row.formattedOriginal?.[prop] || '';
  let current = row[prop]?.trim() || '';

  console.log(`[blur] 字段: ${prop}, 原始值: '${original}', 当前值: '${current}'`);

  // 1. 空值处理
  if (!current) {
    if (original) { // 如果原始值不为空，则视为删除操作
      row[prop] = '';
      await handleFieldChange(row);
    }
    return;
  }

  // 2. 格式校验
  if (current.length !== 4 || !/^\d{4}$/.test(current)) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`);
    row[prop] = original; // 回滚
    return;
  }
  
  // 3. 时间有效性校验
  const hours = parseInt(current.substring(0, 2));
  const minutes = parseInt(current.substring(2, 4));
  if (hours >= 24 || minutes >= 60) {
    message.error('请输入有效的时间(HHmm)');
    row[prop] = original; // 回滚
    return;
  }

  // 4. 格式转换
  const formatted = `${current.substring(0, 2)}:${current.substring(2, 4)}`;
  console.log(`[blur] 转换后的值: '${formatted}'`);

  // 5. 对比并更新
  if (formatted !== original) {
    row[prop] = formatted;
    await handleFieldChange(row);
  } else {
    // 值未变，但格式可能需要统一
    row[prop] = formatted;
  }
}

const handleNumberBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal?.[prop] || ''
  if (current === original) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) < 0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  // 对于布尔值或其他非字符串类型，直接使用原始值，不进行 trim
  const current = typeof row[prop] === 'string' ? row[prop].trim() : row[prop];
  const original = row.formattedOriginal?.[prop];
  
  // 使用 JSON.stringify 进行深比较，以处理不同类型间的比较（例如 false vs ''）
  if (JSON.stringify(current) === JSON.stringify(original)) return;
  
  await handleFieldChange(row);
}

/** 新增：处理普通字段失去焦点事件 */
const handleFieldBlur = async (row: ScheduleRecordVO, field: string) => {
  await handleTextBlur(row, field)
}

/** 列设置 */
const tableColumns = [
  {
    prop: 'inboundFlight',
    label: '进港航班',
    width: 150,
    editable: true,
    editWidth: 120,
    type: '文本'
  },
  { prop: 'flightNo', label: '航班号', width: 120, type: '文本' },
  { prop: 'route', label: '航线', width: 180, type: '文本' },
  { prop: 'machineNo', label: '机号', width: 130, editable: true, editWidth: 100, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  {
    prop: 'preLandingTime',
    label: '预落时间',
    width: 100,
    editable: true,
    editWidth: 100,
    type: '时间'
  },
  {
    prop: 'inboundTime',
    label: '实落时间',
    width: 100,
    editable: true,
    editWidth: 100,
    type: '时间'
  },
  { prop: 'recordDate', label: '日期', width: 120, type: '日期' },
  {
    prop: 'airportStands',
    label: '机位',
    width: 130,
    editable: true,
    editWidth: 100,
    type: '文本'
  },
  { prop: 'remarks', label: '备注', width: 200, editable: true, editWidth: 200, type: '文本' },
  {
    prop: 'quantity',
    label: '数量',
    width: 300,
    type: '复合'
  },
  {
    prop: 'specialRemarks',
    label: '特殊说明',
    width: 200,
    editable: true,
    editWidth: 200,
    type: '文本'
  },
  { prop: 'aircraftType', label: '机型', width: 120, type: '文本' },
  { prop: 'airlineComp', label: '所属公司', width: 120, type: '状态' },
  { prop: 'airlinePattern', label: '航班类型', width: 120, type: '状态' },
  { prop: 'company', label: '所属公司', width: 120, type: '文本' },
  { prop: 'createTime', label: '创建时间', width: 180, type: '时间' },
  { prop: 'pstatus', label: '生产状态', width: 120, type: '状态' }
]

const columnVisibility = ref<Record<string, boolean>>({})
const selectedColumns = ref<string[]>([])
const columnSettingVisible = ref(false)

const initColumnVisibility = () => {
  const visibility: Record<string, boolean> = {}
  const selected: string[] = []

  tableColumns.forEach((column) => {
    visibility[column.prop] = true
    selected.push(column.prop)
  })

  columnVisibility.value = visibility
  selectedColumns.value = selected
}

const openColumnSetting = () => {
  columnSettingVisible.value = true
}

const saveColumnSettings = () => {
  const newVisibility: Record<string, boolean> = {}
  tableColumns.forEach((column) => {
    newVisibility[column.prop] = false
  })
  selectedColumns.value.forEach((prop) => {
    newVisibility[prop] = true
  })
  columnVisibility.value = newVisibility
  columnSettingVisible.value = false
}

/** 打开数量编辑弹窗 */
const openQuantityEdit = (row: ScheduleRecordVO) => {
  currentRow.value = JSON.parse(JSON.stringify(row))
  quantityDialogVisible.value = true
}

/** 新增：打开时间详情弹窗 - 修复初始化逻辑 */
const openTimeDetail = async (id: number) => {
  try {
    loading.value = true
    const data = await ScheduleRecordApi.getTodayEditTime(id)
    if (!data) {
      message.warning('未找到时间详情数据')
      return
    }
    
    // 转换时间格式并初始化 formattedOriginal
    const formattedRow = transformTimeData(data) as any; // 使用 'any' 避免类型检查问题
    
    // 关键修复：为弹窗行数据添加 formattedOriginal
    formattedRow.formattedOriginal = {
      inboundTime: formattedRow.inboundTime || '',
      preLandingTime: formattedRow.preLandingTime || '',
      shiLuoTime: formattedRow.shiLuoTime || '',
      depTime: formattedRow.depTime || '',
      yuFeiTime: formattedRow.yuFeiTime || '',
      shiFeiTime: formattedRow.shiFeiTime || '',
      arrTime: formattedRow.arrTime || '',
      yuHuiTime: formattedRow.yuHuiTime || '',
      shiHui: formattedRow.shiHui || '',
      airportStands: formattedRow.airportStands || '',
      huiWei: formattedRow.huiWei || '',
      yanWu: formattedRow.yanWu || false
    };

    timeDetailData.value = [formattedRow]
    originalTimeData.value = JSON.parse(JSON.stringify([data])) // 保存未格式化的原始响应
    timeDetailDialogVisible.value = true
  } catch (error) {
    message.error('获取时间详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 新增：时间数据转换 */
const transformTimeData = (data: ScheduleRecordVO): ScheduleRecordVO => {
  const timeFields = [
    'inboundTime', 'preLandingTime', 'shiLuoTime', 'depTime',
    'yuFeiTime', 'shiFeiTime', 'arrTime', 'yuHuiTime', 'shiHui'
  ]
  
  const transformed = { ...data }
  
  timeFields.forEach(field => {
    transformed[field] = formatTimeArray(transformed[field])
  })
  
  return transformed
}

/** 核心：虚拟化表格列配置 */
const tableV2Columns = computed<Column<ScheduleRecordVO>[]>(() => {
  const dynamicColumns = tableColumns
    .filter((column) => columnVisibility.value[column.prop])
    .map((column) => ({
      key: column.prop,
      title: column.label,
      dataKey: column.prop,
      width: column.width || 120,
      cellRenderer: ({ cellData, rowData }) => {
        const row = rowData as ScheduleRecordVO
        const cellValue = cellData?.toString() || ''
        const isDisabled = row.pstatus === 12

        if (column.prop === 'quantity') {
          return (
            <div
              style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
              onClick={() => openQuantityEdit(row)}
            >
              <div style="display: flex; font-weight: 500; font-size: 12px;">
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">J</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">S</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">G</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">Y</div>
              </div>
              <div style="display: flex; font-size: 12px;">
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.crewSaleQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.bussClassSaleQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.premEcoClassSaleQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.ecoClassSaleQty || '-'}</div>
              </div>
              <div style="display: flex; font-size: 12px;">
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.crewQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.bussClassQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.premEcoClassQty || '-'}</div>/
                <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{row.ecoClassQty || '-'}</div>
              </div>
            </div>
          )
        }

        if (column.editable) {
          if (isTimeColumn(column.prop)) {
            return (
              <ElInput
                modelValue={cellValue}
                onUpdate:modelValue={(val) => { row[column.prop] = val }}
                placeholder={`请输入${column.label}(HHmm)`}
                clearable
                class={`!w-${column.editWidth || 100}px`}
                onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
                onBlur={() => handleColumnTimeBlur(row, column.prop)}
                show-word-limit
                disabled={isDisabled}
              />
            )
          }

          if (isNumberColumn(column.prop)) {
            return (
              <ElInput
                modelValue={cellValue}
                onUpdate:modelValue={(val) => { row[column.prop] = val }}
                placeholder={`请输入${column.label}`}
                clearable
                class={`!w-${column.editWidth || 100}px`}
                onInput={(e) => handleNumberInput(row, column.prop, e.target.value)}
                onBlur={() => handleNumberBlur(row, column.prop)}
                show-word-limit
                type="number"
                min="0"
                disabled={isDisabled}
              />
            )
          }

          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => { row[column.prop] = val }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onBlur={() => handleTextBlur(row, column.prop)}
              show-word-limit
              disabled={isDisabled}
            />
          )
        }

        if (column.prop === 'pstatus') {
          return (
            <ElTag type="primary" class="flex items-center justify-center">
              {getStatusLabel(cellData)}
            </ElTag>
          )
        }

        if (column.prop === 'airlineComp') {
          return h(DictTag, { type: DICT_TYPE.PPLAN_AIRLINE_ID, value: row.airlineComp })
        }
        if (column.prop === 'airlinePattern') {
          return h(DictTag, { type: DICT_TYPE.PPLAN_AIRLINE_TYPE, value: row.airlinePattern })
        }

        if (column.prop === 'createTime') {
          const formatted = formatDate(cellData) || '-'
          return (
            <ElTooltip content={formatted} placement="top">
              <span class="flex items-center justify-center">
                <ElIcon class="mr-2"><Timer /></ElIcon>
                {formatted}
              </span>
            </ElTooltip>
          )
        }

        if (isTimeColumn(column.prop)) {
          const formatted = formatDisplayTime(cellValue) || '-'
          return (
            <ElTooltip content={formatted} placement="top">
              <span class="flex items-center justify-center">{formatted}</span>
            </ElTooltip>
          )
        }

        if (column.prop === 'route') {
          const depLoc = row.depLoc || ''
          const arrLoc = row.arrLoc || ''
          const routeText = depLoc && arrLoc ? `${depLoc} - ${arrLoc}` : '-'
          return (
            <ElTooltip content={routeText} placement="top">
              <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ">
                {routeText}
              </div>
            </ElTooltip>
          )
        }

        if (column.prop === 'remarks' || column.prop === 'specialRemarks') {
          return (
            <ElTooltip content={cellValue || '-'} placement="top">
              <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center justify-center">
                {cellValue || '-'}
              </div>
            </ElTooltip>
          )
        }

        if (column.prop === 'flightNo') {
          return (
            <span 
              class="flex items-center justify-center text-primary cursor-pointer hover:underline"
              onClick={() => openTimeDetail(row.id)}
            >
              {cellValue}
            </span>
          )
        }

        return <span class="flex items-center justify-center">{cellValue || '-'}</span>
      }
    }))

  const actionColumn: Column<ScheduleRecordVO> = {
    key: 'actions',
    title: '操作',
    width: 200,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as ScheduleRecordVO
      return (
        <div style="display: flex; align-items: center; justify-center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openForm('update', row.flightNo)}
          >
            查看详情
          </ElButton>

          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openAddForm(row.flightNo, row.recordDate)}
          >
            加餐
          </ElButton>

          <ElDropdown
            v-slots={{
              dropdown: () => (
                <ElDropdownMenu>
                  {pstatusList.map((item) => (
                    <ElDropdownItem
                      key={item.value}
                      onClick={() => handleStatusChange(row, item.value)}
                    >
                      {item.label}
                    </ElDropdownItem>
                  ))}
                </ElDropdownMenu>
              )
            }}
          >
            <ElButton type="primary" link size="small">
              <ElIcon class="mr-1"><DArrowRight /></ElIcon>
              更多
            </ElButton>
          </ElDropdown>
        </div>
      )
    }
  }

  return [...dynamicColumns, actionColumn]
})

/** 辅助配置 */
const tableRowClassName = ({ rowData }: { rowData: any }) => {
  return rowData?.markStatus === 1 ? 'row-first' : ''
}

/** 关闭的方法 */
const handleClose = () => {
  timeDetailDialogVisible.value = false
   handleQuery()
}

/** 初始化 */
onMounted(() => {
  initColumnVisibility()
  getList()
})

watch(selectedColumns, () => {}, { deep: true })
</script>

<style scoped>
:deep(.el-table__row.row-first),
:deep(.el-table-v2__row.row-first) {
  background-color: #f26a6e !important;
}

.column-setting-group {
  max-height: 300px;
  padding-right: 10px;
  overflow-y: auto;
}

:deep(.column-setting-group .el-checkbox) {
  display: block;
  margin-bottom: 10px;
}

:deep(.el-table-v2__cell) {
  padding: 4px 8px !important;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table-v2__header) {
  /* background-color: #f8fafc !important; */

  /* border-bottom: 1px solid #e6e6e6; */
}

:deep(.el-table-v2__header-cell) {
  padding: 8px !important;
  font-weight: 500;
  color: #333;
}

:deep(.el-input__inner) {
  width: 100% !important;
  min-height: 28px !important;
}

:deep(.el-input) {
  margin: 0 !important;
}

.overflow-hidden {
  overflow: hidden;
}

.whitespace-nowrap {
  white-space: nowrap;
}

.text-ellipsis {
  text-overflow: ellipsis;
}

:deep(.el-tooltip:hover .text-ellipsis) {
  color: #409eff !important;
  cursor: help;
}

:deep(.el-dialog__body .el-table) {
  max-height: 50vh;
  overflow-y: auto;
}

:deep(.el-dialog__body .el-input) {
  margin-bottom: 0;
}

:deep(.el-switch) {
  --el-switch-on-color: var(--el-color-primary);
  --el-switch-off-color: var(--el-border-color-base);
}
</style>